package middlewares

import (
	"net/http"
	"strings"

	"myapi/pkg/utils"

	"github.com/gin-gonic/gin"
)

type Auth struct{}

func NewAuth() *Auth {
	return &Auth{}
}

func (a *Auth) Authenticate() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取 Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			utils.ErrorResponse(c, http.StatusUnauthorized, "Authorization header is required")
			c.Abort()
			return
		}

		// 检查 token 格式
		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			utils.ErrorResponse(c, http.StatusUnauthorized, "Authorization header format must be Bearer {token}")
			c.Abort()
			return
		}

		// 获取 token
		token := parts[1]

		// 这里应该验证 token，示例中简化处理
		// 实际应用中应该使用 JWT 或其他认证机制
		if token == "" {
			utils.ErrorResponse(c, http.StatusUnauthorized, "Invalid token")
			c.Abort()
			return
		}

		// 验证通过，可以将用户信息存储在上下文中
		//c.Set("userID", userID)

		c.Next()
	}
}
